package com.jh.paymentchannel.service;

import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.BranchNo;
import com.jh.paymentchannel.pojo.JFRegister;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class JFQuickTopupRequest implements TopupRequest{

	private static final Logger log = LoggerFactory.getLogger(JFQuickTopupRequest.class);
	
	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;
	
	@Autowired
	private BranchbankBussiness branchbankBussiness;
	
	@Autowired
	private Util util;
	
	@Value("${payment.ipAddress}")
	private String ipAddress;
	
	@Value("${jf.partnerNo}")
	private String partnerNo;
	
	@Value("${jf.key}")
	private String Key;
	
	/*private static String partnerNo = "UDp0WZ64";
	
	private static String Key = "UD1RDD194BDVDPCCUB56434C39EWZE98";*/
	
	private static final Charset UTF_8 = StandardCharsets.UTF_8;
	
	@Override
	public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode,
			String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {
		log.info("ipAddress====="+ipAddress);
		log.info("partnerNo====="+partnerNo);
		log.info("Key====="+Key);
		 Map<String, String>  map = new HashMap<String, String>();
			/**首先拿到用户的userid, 如果用户已经存在，那么直接拿用户的sdjuserid, 如果用户的默认结算卡已经和当前不一样了。 需要重新注册 **/
			RestTemplate restTemplate=new RestTemplate();
			URI uri = util.getServiceUrl("transactionclear", "error url request!");
			String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
			MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
			requestEntity.add("order_code", ordercode);
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("RESULT================"+result);
			JSONObject jsonObject;
			JSONObject resultObj;
			try {
				jsonObject = JSONObject.fromObject(result);
				resultObj = jsonObject.getJSONObject("result");
			} catch (Exception e) {
				log.error("查询订单信息出错");
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "没有该订单信息");
				return map;
			}
			String realamount = resultObj.getString("realAmount");
			String userid = resultObj.getString("userid");
			//通道id
			String channelid = resultObj.getString("channelid");
			//费率
			String rate = resultObj.getString("rate");
			//银行卡
			String bankCard = resultObj.getString("bankcard");
			
			restTemplate=new RestTemplate();
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/bank/default/userid";
			requestEntity  = new LinkedMultiValueMap<String, String>();
			requestEntity.add("user_id", userid);
			result = restTemplate.postForObject(url, requestEntity, String.class);
			
			log.info("RESULT================"+result);
			try {
				jsonObject =  JSONObject.fromObject(result);
				resultObj  =  jsonObject.getJSONObject("result");
			} catch (Exception e) {
				log.error("查询默认结算卡出错");
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "查询默认结算卡有误");
				return map;
			}
			
			if(resultObj.isNullObject()){
				
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "没有结算卡");
				return map;
			}
			
			String cardNo = resultObj.getString("cardNo");
			String userName = resultObj.getString("userName");
			/**身份证号*/
			String idcard   = resultObj.getString("idcard");
			String phone    = resultObj.getString("phone");
			//开户行所在省
			String provinceOfBank = resultObj.getString("province");
			
			System.out.println("provinceOfBank"+provinceOfBank);
			//开户行所在市
			String cityOfBank = resultObj.getString("city");
			
			System.out.println("cityOfBank"+cityOfBank);
			//银行名称
			String bankName = resultObj.getString("bankName");
			//支行名称
			String bankBranchName = resultObj.getString("bankBranchName");
			
			String expiredTime = resultObj.getString("expiredTime");
			
			String securityCode = resultObj.getString("securityCode");
			
			String cardType = resultObj.getString("cardType");
			
			String bankBranchNo;
			try {
				bankBranchNo = branchbankBussiness.getNumByName(bankBranchName);
			} catch (Exception e1) {
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "查询支行联行号有误");
				return map;
			}
			System.out.println("bankBranchNo"+bankBranchNo);
			
			restTemplate=new RestTemplate();
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/bank/default/cardno";
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("cardno", bankCard);
			requestEntity.add("type", "0");
			result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("接口/v1.0/user/bank/default/cardno--RESULT================"+result);
			try {
				jsonObject =  JSONObject.fromObject(result);
				resultObj  =  jsonObject.getJSONObject("result");
			} catch (Exception e) {
				log.error("查询银行卡信息出错");
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "查询银行卡信息有误");
				return map;
			}
			if(resultObj==null){
				return null;
			}
			
			String cardName = resultObj.getString("bankName");
			
			String bankname = Util.queryBankNameByBranchName(bankName);
			String cardname = Util.queryBankNameByBranchName(cardName);
			
			//根据银行名称查询得到银行信息
			BranchNo findByBankName;
			try {
				findByBankName = branchbankBussiness.findByBankName(bankname);
			} catch (Exception e) {
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "查询银行信息有误");
				return map;
			}
			//银行总行联行号
			String inBankUnitNo = findByBankName.getBankNo();
			
			JFRegister jfRegister;
			try {
				jfRegister = topupPayChannelBusiness.getJFRegister(Long.parseLong(userid));
			} catch (Exception e) {
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "查询用户进件信息有误");
				return map;
			}
			
			
			if(provinceOfBank==null||"".equals(provinceOfBank)||"null".equals(provinceOfBank)){
				provinceOfBank = "";
			}
			
			if(cityOfBank==null||"".equals(cityOfBank)||"null".equals(cityOfBank)){
				cityOfBank = "";
			}
			
			if(bankBranchNo==null||"".equals(bankBranchNo)||"".equals(bankBranchNo)){
				bankBranchNo = "";
			}
			
			if(bankBranchName==null||"".equals(bankBranchName)||"null".equals(bankBranchName)){
				bankBranchName = "";
			}
			
				
				if(jfRegister == null){
					log.info("用户需要进件========");
					//jfRegister为空表示用户需要进件
					Map maps = new HashMap();
					maps.put("resp_code", "success");
					maps.put("channel_type", "jf");
					maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/tojfbankinfo"+"?bankName="+URLEncoder.encode(bankname,"UTF-8")+"&bankBranchId="+bankBranchNo+
							"&bankNo="+cardNo+"&bankCard="+bankCard+"&cardName="+URLEncoder.encode(cardname,"UTF-8")+"&amount="+amount+"&ordercode="+ordercode+"&provinceOfBank="+URLEncoder.encode(provinceOfBank,"UTF-8")+"&cityOfBank="+URLEncoder.encode(cityOfBank,"UTF-8")+
							"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+"&cardType="+URLEncoder.encode(cardType,"UTF-8")+"&isRegister=0");
					return maps;
			        
					
				}else if(!rate.equals(jfRegister.getRate())){
					//用户费率发生变更，需要重新进件
					log.info("用户费率变更，需要重新进件======");
					Map maps = new HashMap();
					maps.put("resp_code", "success");
					maps.put("channel_type", "jf");
					maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/tojfbankinfo"+"?bankName="+URLEncoder.encode(bankname,"UTF-8")+"&bankBranchId="+bankBranchNo+
							"&bankNo="+cardNo+"&bankCard="+bankCard+"&cardName="+URLEncoder.encode(cardname,"UTF-8")+"&amount="+amount+"&ordercode="+ordercode+"&provinceOfBank="+URLEncoder.encode(provinceOfBank,"UTF-8")+"&cityOfBank="+URLEncoder.encode(cityOfBank,"UTF-8")+
							"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+"&cardType="+URLEncoder.encode(cardType,"UTF-8")+"&isRegister=0");
					return maps;
				
				
				}else if(topupPayChannelBusiness.getJFRegister(Long.parseLong(userid), cardNo) == null) {
					//用户默认提现卡发生变更，需要重新进件
					log.info("用户默认提现卡变更，需要重新进件=====");
					Map maps = new HashMap();
					maps.put("resp_code", "success");
					maps.put("channel_type", "jf");
					maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/tojfbankinfo"+"?bankName="+URLEncoder.encode(bankname,"UTF-8")+"&bankBranchId="+bankBranchNo+
							"&bankNo="+cardNo+"&bankCard="+bankCard+"&cardName="+URLEncoder.encode(cardname,"UTF-8")+"&amount="+amount+"&ordercode="+ordercode+"&provinceOfBank="+URLEncoder.encode(provinceOfBank,"UTF-8")+"&cityOfBank="+URLEncoder.encode(cityOfBank,"UTF-8")+
							"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+"&cardType="+URLEncoder.encode(cardType,"UTF-8")+"&isRegister=0");
					return maps;
				
				}else{
					//用户进件信息未发生变更，发起交易
					log.info("用户进件信息未发生变更，发起交易=======");					
					Map maps = new HashMap();
					maps.put("resp_code", "success");
					maps.put("channel_type", "jf");
					maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/tojfbankinfo"+"?bankName="+URLEncoder.encode(bankname,"UTF-8")+"&bankBranchId="+bankBranchNo+
							"&bankNo="+cardNo+"&bankCard="+bankCard+"&cardName="+URLEncoder.encode(cardname,"UTF-8")+"&amount="+amount+"&ordercode="+ordercode+"&provinceOfBank="+URLEncoder.encode(provinceOfBank,"UTF-8")+"&cityOfBank="+URLEncoder.encode(cityOfBank,"UTF-8")+
							"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+"&cardType="+URLEncoder.encode(cardType,"UTF-8")+"&isRegister=1");
					return maps;
					
				}
				
			

	}
	

}
